/*
 * getStorageDir

 */

const os = require("os");
const fs = require("fs");
const path = require("path");
const { app } = require("electron");
const { spawn } = require("child_process");
const dayjs = require("dayjs");
const pkg = require("../package.json");

function get7ZipPath() {
  if (process.platform === "win32") {
    return "7z.exe";
  }
  return "7z.exe";
}

const getFileStorageDir = () => {
  const userHomeDir = os.userInfo().homedir;
  const storageDir = path.normalize(
    userHomeDir + "/Documents/" + pkg.name + "/"
  );
  return storageDir;
};

const getFileDir = (
  fileName = `/upload/${dayjs().format("YYYYMMDD_HHmmss")}/`
) => {
  const fileDir = path.normalize(getFileStorageDir() + "/file");

  if (!fs.existsSync(fileDir)) {
    fs.mkdirSync(fileDir);
  }
  const filePath = path.normalize(fileDir + fileName);
  return filePath;
};

const unzip = (zipFilePath, password) => {
  return new Promise((resolve) => {
    const softName = get7ZipPath();
    // 资源路径不同
    let softwarePath = "";

    if (app.isPackaged) {
      // 打包后
      softwarePath = path.join(app.getAppPath(), "..", softName);
    } else {
      // 打包前
      softwarePath = path.join(
        app.getAppPath(),
        "zipFile",
        "extraResources/7-Zip/",
        softName
      );
    }
    errorLog(zipFilePath);
    // 检查程序是否存在
    // if (!fs.existsSync(softwarePath)) {
    //   resolve();
    //   return false;
    // }
    const outPath = path.join(
      app.getAppPath(),
      "..",
      `files_${dayjs().format("YYYYMMDD_HHmmss")}`
    );

    // "C:\Program Files\7-Zip\7z.exe" x -p123456 –oD:\Temp\7ziptext\test D:\Temp\7ziptext\7ziptext.zip
    const stamp = spawn(
      softwarePath,
      ["x", `-p${password}`, `-o${outPath}`, zipFilePath],
      { stdio: ["ignore"], detached: true, shell: false, windowsHide: true }
    );

    stamp.stdout.on("data", (data) => {
      console.log(`stdout: ${data}`);
      // resolve()
    });

    stamp.stderr.on("data", (data) => {
      console.log(`stderr: ${data}`);
      console.error(data);
      // resolve()
    });

    stamp.on("close", (code) => {
      console.log(`子进程退出码：${code}`);
      resolve(outPath);
    });
  });
};

const deleteFolder = (folderPath) => {
  if (fs.existsSync(folderPath)) {
    fs.readdirSync(folderPath).forEach((file) => {
      const curPath = path.join(folderPath, file);
      if (fs.lstatSync(curPath).isDirectory()) {
        // 递归删除子文件夹
        deleteFolder(curPath);
      } else {
        // 删除文件
        fs.unlinkSync(curPath);
      }
    });
    // 删除文件夹
    fs.rmdirSync(folderPath);
  }
};

const time_string = (timeString) => {
  const date = new Date(timeString);
  const Y = date.getFullYear();
  const M = date.getMonth() + 1;
  const D = date.getDate().toString().padStart(2, "0");
  const H = date.getHours().toString().padStart(2, "0");
  const hM = date.getMinutes().toString().padStart(2, "0");
  const S = date.getSeconds().toString().padStart(2, "0");
  const stff = `${Y}${M.toString().padStart(2, "0")}${D}${H}${hM}${S}`;
  return stff;
};

// 移动文件的函数
const moveFile = (sourcePath, targetFolder, fileName) => {
  // 目标文件路径
  const targetPath = targetFolder + fileName;

  // 确保目标文件夹存在
  fs.access(targetFolder, fs.constants.F_OK, (err) => {
    if (err) {
      fs.mkdir(targetFolder, { recursive: true }, (mkdirErr) => {
        if (mkdirErr) throw mkdirErr;
        copyFile();
      });
    } else {
      copyFile();
    }
  });

  function copyFile() {
    fs.copyFile(sourcePath, targetPath, (copyErr) => {
      if (copyErr) throw copyErr;
      console.log("文件复制成功");
    });
  }
};

const errorLog = (error) => {
  const data = {
    error: error,
  };
  const jsonData = JSON.stringify(data, null, 2);

  // 文件路径
  const filePath = "./log.json";

  // 写入文件
  fs.appendFile(filePath, jsonData, (err) => {});
};

// 本地路径

const dirPath = () => {
  return path.join(app.getAppPath(), "..");
};

module.exports = {
  getFileDir,
  unzip,
  deleteFolder,
  time_string,
  moveFile,
  dirPath,
};
